package com.wtwd.campus.receiver;

import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.entity.MqGeneralSwitchResult;
import com.wtwd.campus.entity.MqMessage;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.DeviceSettingService;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@MsgType(value = Constants.SHUT_DOWN_SILENT)
public class ShutDownSilentReceiverHandler implements IReceiverHandler {
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private DeviceSettingService deviceSettingService;
    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralSwitchResult mqGeneralSwitchResult = (MqGeneralSwitchResult) mqMessage.getObject();
        String imei = mqGeneralSwitchResult.getImei();
        String commandNumber = mqGeneralSwitchResult.getCommandNumber();
        Integer flag = mqGeneralSwitchResult.getResult();
        String deviceDate = mqGeneralSwitchResult.getDeviceDate();
        //处理指令回复的时间
        Long time = getTime(deviceDate, commandNumber);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if(deviceInfo!=null){
            //修改设备信息
            deviceInfo.setLastUpTime(System.currentTimeMillis());
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            //修改设备设置信息
            deviceSettingService.modifySilentSwitchByDeviceId(deviceInfo.getDeviceId(),flag);
            //删除缓存中的指令
            String delKey=Constants.SHUT_DOWN_SILENT.concat("-").concat(commandNumber);
            receiverUtils.deleteCommandInRedis(imei, delKey);
            //完善指令下发记录
            receiverUtils.completeCommandRecord(Constants.SHUT_DOWN_SILENT, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }
}
